package com.whz.work;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @ClassName SocketDemo
 * @Description TODO 从Socket类中获取到OutputStream和InputStream
 * 发送文本到远程应用程序,通常需要使用返回的OutputStream对象创建一个PrintWriter对象
 * 从连接的另一端接受字节流,需要调用Socket类的getInputStream()方法
 * @Author hong-zhi
 * @Date 2021/5/27 15:36
 * @Version 1.0
 */
@Slf4j
public class SocketDemo {
    public static void client(String ip, int port) {
        try (Socket socket = new Socket(ip, port)) {
            OutputStream os = socket.getOutputStream();
            boolean autoFlush = true;
            PrintWriter out = new PrintWriter(os, autoFlush);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 发送HTTP请求到web服务器
            out.println("GET / HTTP/1.1");
            out.println("Host: " + ip + ":" + port);
            out.println("Connection: Close");
            out.println("你好!");

            // 读取响应
            boolean loop = true;
            StringBuffer sb = new StringBuffer(8096);
            while (loop) {
                if(in.ready()) {
                    int i = 0;
                    while (i != -1) {
                        i = in.read();
                        sb.append((char) i);
                    }
                    loop = false;
                }
                Thread.currentThread().sleep(50);
            }
            log.info("从服务器上接受到的响应");
            log.info(sb.toString());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
